package com.aube.interact.taste.goods;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.aube.interact.taste.IPluginBaseListener;
import com.aube.interact.taste.model.ImageItem;
import com.huyn.baseframework.dynamicload.video.model.GoodsItem;
import com.huyn.baseframework.dynamicload.video.model.GoodsModel;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.utils.Utils;

/**
 * Created by hill on 10/24.
 */
public class GoodsHotpotLayout extends FrameLayout {
    private String TAG = "Aube/GoodsHotpotLayout";

    private Context mContext;
    private FrameLayout mRoot;

    private IAddFavorListener iAddFavorListener;

    private ChannelDetail mChannel;

    private IPluginBaseListener mBaseListner;
    private GoodsDetailLayout mGoodsDetailLayout;

    private SmallGoodsItem mSmallGoodsItem = null;
    private int mSmallGoodsItem_X = 0, mSmallGoodsItem_Y = 0;

    public GoodsHotpotLayout(Context context) {
        this(context, null);
    }
    public GoodsHotpotLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public GoodsHotpotLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        mRoot = this;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);

        if(mHotpotView != null && mGoodsHotpotVisible) {
            mHotpotView.layout(mHotpotX, mHotpotY, mHotpotX + mHotpotView.getMeasuredWidth(), mHotpotY + mHotpotView.getMeasuredHeight());
        }

        if(mSmallGoodsItem != null) {
            mSmallGoodsItem.layout(mSmallGoodsItem_X, mSmallGoodsItem_Y, mSmallGoodsItem.getMeasuredWidth()+ mSmallGoodsItem_X, mSmallGoodsItem.getMeasuredHeight()+ mSmallGoodsItem_Y);
        }
    }

    public void bindVideo(ChannelDetail channelDetail) {
        this.mChannel = channelDetail;
    }

    public void bindController(GoodsDetailLayout mGoodsDetailLayout, IPluginBaseListener listener) {
        this.mGoodsDetailLayout = mGoodsDetailLayout;
        this.mBaseListner = listener;
    }

    private GoodsModel mData;

    private ImageItem mMiddleSizeHotpot = null;
    private int mHotpotX=0, mHotpotY=0;
    private GoodsHotpotView mHotpotView;
    public void showHotpot(GoodsModel data, final IAddFavorListener listener) {
        Utils.Log(TAG, "[showHotpot]");
        int width = getWidth();
        int height = getHeight();
        if(mMiddleSizeHotpot == null) {
            int GAP = (int) ((1 - 0.66f - 0.247f) * width / 3);

            int mWidth = (int) (width * 0.66f);
            int mHeight = (int) (width * 0.66 * 9 / 16);

            mMiddleSizeHotpot = new ImageItem(mWidth, mHeight, GAP, (height - mHeight) / 2);
        }

        if(mGoodsHotpotFullscreen) {
            mHotpotX = mHotpotY = 0;
        } else {
            mHotpotX = mMiddleSizeHotpot.x;
            mHotpotY = mMiddleSizeHotpot.y;
        }

        this.mData = data;
        this.iAddFavorListener = listener;
        Utils.Log(TAG, "mGoodsHotpotFullScreen = " + mGoodsHotpotFullscreen);
        LayoutParams params = mGoodsHotpotFullscreen ? new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                                                    : new LayoutParams(mMiddleSizeHotpot.width, mMiddleSizeHotpot.height);
        if(mHotpotView != null && mHotpotView.getParent() != null)
            removeView(mHotpotView);
        mHotpotView = new GoodsHotpotView(getContext());
        mHotpotView.setProgressListener(new GoodsHotpotView.IProgressListener() {
            @Override
            public int getCurrentProgress() {
                if(listener != null)
                    return listener.getProgress();
                return 0;
            }
        }, data.timelineCircleRespVoList);
        mHotpotView.setOnHotpotClickListener(new GoodsHotpotView.OnHotpotClickListener() {
            @Override
            public void onClick(int x, int y) {
                mHotpotView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                Utils.Log(TAG, "mHotpotView onClick.  mHotpotView width = " + mHotpotView.getMeasuredWidth() + ", mHotpoView height = " + mHotpotView.getMeasuredHeight());
                showGoodsDetailLayout(false);
            }
        });
        addView(mHotpotView, params);

        mHotpotView.setVisibility(mGoodsHotpotVisible ? VISIBLE : GONE);

        showGoodsThumbnail();
    }

    /**
     * 显示商品缩略图, 与热点圆圈一起出现
     */
    private void showGoodsThumbnail() {
        Utils.Log(Utils.LogType.DEBUG, TAG, "showGoodsThumbnail");

        if(mSmallGoodsItem != null && mSmallGoodsItem.getParent() != null)
            removeView(mSmallGoodsItem);

        // initialize SmallGoodsItem
        mSmallGoodsItem = new SmallGoodsItem(getContext());
        mSmallGoodsItem.fillData(mData);
        mSmallGoodsItem.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showGoodsDetailLayout(true);
            }
        });

        // setup view & its location
        mSmallGoodsItem.setVisibility(mGoodsHotpotVisible ? VISIBLE : GONE);
        mSmallGoodsItem_X = (int) (mData.getGoodsTagLeftTop_X() * getMeasuredWidth());
        mSmallGoodsItem_Y = (int) (mData.getGoodsTagLeftTop_Y() * getMeasuredHeight());
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        addView(mSmallGoodsItem, params);

        Utils.Log(TAG, "[showGoodsThumbnail] percent x  = " + mData.getGoodsTagLeftTop_X()+ ", y = " + mData.getGoodsTagLeftTop_Y() + ", width = " + getMeasuredWidth());
        Utils.Log(TAG, "[showGoodsThumbnail] x = " + mSmallGoodsItem_X + ", y = " + mSmallGoodsItem_Y);

        // finally, animate it
        mSmallGoodsItem.startAlphaInAnim();
    }

    private void showGoodsDetailLayout(boolean bFromThumbnail) {
        Utils.Log(TAG, "[showGoodsDetaiLayout]");
        setupGoodsDetailLayout(bFromThumbnail);

        //hide text
        mSmallGoodsItem.alphaOutTitle(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animator) {
                mGoodsDetailLayout.startAnim();

                //showbg
                if(mBaseListner != null)
                    mBaseListner.onStartBgMaskAnim(true);

                setVisibility(GONE);
            }
        });
    }

    private static Bitmap loadBitmapFromView(GoodsHotpotView v) {
        try {
            Bitmap b = Bitmap.createBitmap( v.getRadius(), v.getRadius(), Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(b);
            v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
            v.draw(c);
            return b;
        } catch (Exception e) {
            Utils.Log("Aube/GoodsHotpotLayout", "[loadBitmapFromView] exception : " + e);
            return null;
        }
    }

    public void setupGoodsDetailLayout(boolean bFromThumbnail) {
        // first, pause player
        if(mBaseListner != null)
            mBaseListner.onClickToGoodsDetail();

        // then, fill data
        mGoodsDetailLayout.fillData(mData, iAddFavorListener, null, null);

        // finally, setup view & pre anima layout
        if(bFromThumbnail) {
            int[] location = new int[2];
            location = mSmallGoodsItem.getGoodsImgLocation();
            int size = mSmallGoodsItem.getGoodsImgSize();
            mGoodsDetailLayout.setupPreAnimLayout(size, location[0], location[1], new GoodsDetailLayout.IAnimEndListener() {
                @Override
                public void onOveralAnimEnd() {
                    setVisibility(VISIBLE);
                    mSmallGoodsItem.alphaInTitle();
                }

                @Override
                public void onStartReverseAnim() {
                    if(mBaseListner != null) {
                        mBaseListner.resumePlayer();
                        mBaseListner.onStartBgMaskAnim(false);
                    }
                }
            });
        } else {
            int[] location = new int[2];
            location = mHotpotView.getCoordinate();
            int size = mHotpotView.getRadius();
            mGoodsDetailLayout.setupPreAnimLayout(size, location[0], location[1], new GoodsDetailLayout.IAnimEndListener() {
                @Override
                public void onOveralAnimEnd() {
                    setVisibility(VISIBLE);
                    mSmallGoodsItem.alphaInTitle();
                }

                @Override
                public void onStartReverseAnim() {
                    if(mBaseListner != null) {
                        mBaseListner.resumePlayer();
                        mBaseListner.onStartBgMaskAnim(false);
                    }
                }
            });
        }
    }

    public void hideGoods() {
    }

    public boolean goodsViewRemoveable() {
        return false;
    }

    public void onDestroy() {
        if(mHotpotView != null) {
//            removeView(mHotpotView);
//            mHotpotView = null;
            mHotpotView.setVisibility(GONE);
        }

        if(mSmallGoodsItem != null && !mSmallGoodsItem.IsAnimating()) {
            mSmallGoodsItem.startGoodsTextCollapseAnim();
        }
    }

    private boolean mGoodsHotpotFullscreen = true;
    private boolean mGoodsHotpotVisible = true;

    /**
     * 随着多镜头主屏幕切换尺寸
     * @param fullscreen
     */
    public void switchSize(boolean fullscreen) {
        mGoodsHotpotFullscreen = fullscreen;
        if(mHotpotView != null && mMiddleSizeHotpot != null) {
            ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f);
            anim.setDuration(300);
            anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();

                    ViewGroup.LayoutParams param = mHotpotView.getLayoutParams();
                    if(mGoodsHotpotFullscreen) {
                        param.width = (int) (mMiddleSizeHotpot.width + (getWidth()-mMiddleSizeHotpot.width)*value);
                        param.height = (int) (mMiddleSizeHotpot.height + (getHeight()-mMiddleSizeHotpot.height)*value);
                        mHotpotX = (int) (mMiddleSizeHotpot.x*(1-value));
                        mHotpotY = (int) (mMiddleSizeHotpot.y*(1-value));
                    } else {
                        param.width = (int) (mMiddleSizeHotpot.width + (getWidth()-mMiddleSizeHotpot.width)*(1-value));
                        param.height = (int) (mMiddleSizeHotpot.height + (getHeight()-mMiddleSizeHotpot.height)*(1-value));
                        mHotpotX = (int) (mMiddleSizeHotpot.x*(value));
                        mHotpotY = (int) (mMiddleSizeHotpot.y*(value));
                    }
                    mHotpotView.setLayoutParams(param);
                    requestLayout();
                }
            });
            anim.start();
        }
    }

    /**
     * 是否展示热点
     * @param display
     */
    public void diaplayHotpot(boolean display) {
        mGoodsHotpotVisible = display;
        if(mHotpotView != null)
            mHotpotView.setVisibility(display ? VISIBLE : GONE);
        if(mSmallGoodsItem != null)
            mSmallGoodsItem.setVisibility(display ? VISIBLE : GONE);
    }

    public interface IAddFavorListener {
        public void doFavorEvent(GoodsItem item);
        public void manageTool();
        public void cancelFavor(String id);
        public int[] getCartLocation();
        public float[] getCardPosition();
        public int getProgress();
        public void hideFavorCart();
    }

}
